package com.sheng.project.security.webmvc.property;

import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpHeaders;

import java.util.HashMap;
import java.util.Map;

/**
 * 跨域相关应用属性配置
 *
 * @author by ls
 * @date 2023/9/8
 */
@Getter
@ConfigurationProperties(prefix = "application.cors", ignoreUnknownFields = false)
@RefreshScope
public class CorsApplicationProperties {

    private final Map<String, CorsConfiguration> configurations = new HashMap<>();

    public CorsApplicationProperties() {
        CorsConfiguration defaultCorsConfiguration = new CorsConfiguration();
        String all = "*";
        defaultCorsConfiguration.setAllowedPath("/**");
        defaultCorsConfiguration.addAllowedHeader(all);
        defaultCorsConfiguration.addAllowedMethod(all);
        defaultCorsConfiguration.addAllowedOrigin("http://another-example.com");

        defaultCorsConfiguration.addExposedHeader(HttpHeaders.SET_COOKIE);
        defaultCorsConfiguration.setAllowCredentials(true);
        defaultCorsConfiguration.setMaxAge(1800L);
        this.configurations.put("_def", defaultCorsConfiguration);
    }

    @Getter
    public static class CorsConfiguration extends org.springframework.web.cors.CorsConfiguration {

        private String allowedPath;

        public void setAllowedPath(String allowedPath) {
            this.allowedPath = allowedPath;
        }
    }
}
